package gosee

import (
	"net/http"
	"os"
	"strings"
)

type HandlerFunc func(c *Context)

type Engine struct {
	*RouterGroup
	router *router
	groups []*RouterGroup
	// 模板
	Template           *Template
	Cache              *Cache
	MaxMultipartMemory int64
}

func New() *Engine {
	engine := &Engine{
		router:             newRouter(),
		MaxMultipartMemory: 32 << 20,
	}
	engine.RouterGroup = &RouterGroup{engine: engine}
	engine.groups = []*RouterGroup{engine.RouterGroup}
	engine.Template = NewTemplate()
	// engine.Static("/static", engine.Template.Config.staticPath)
	// pattern := filepath.Join(engine.Template.Config.templatePath + "*" + engine.Template.Config.templateSuffix)
	// fmt.Printf("模板路径：%s\n", pattern)
	// if err := engine.Template.Load(pattern); err != nil {
	// 	panic(err)
	// }
	// //输出所有的模板
	// for _, t := range engine.Template.Templates.Templates() {
	// 	fmt.Println("模板文件：" + t.Name())
	// }
	engine.Cache = NewCache()
	return engine
}

func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c := newContext(w, r)
	c.Engine = engine

	// 1. 收集所有中间件(全局+匹配路由组)
	handlers := collectMiddlewares(engine, r)

	// 2. 添加路由处理器
	handlers = append(handlers, func(c *Context) {
		engine.router.handler(c)
	})

	c.Middleware.handlers = handlers
	c.Middleware.index = -1
	c.Next()
}

func Default() *Engine {
	engine := New()
	engine.Use(Logger(), Recovery())
	return engine
}

func (engine *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, engine)
}

func (engine *Engine) Static(relativePath, root string) {
	if _, err := os.Stat(root); err != nil {
		panic("静态文件根目录不存在: " + root)
	}
	if !strings.HasPrefix(relativePath, "/") {
		relativePath = "/" + relativePath
	}
	handler := http.StripPrefix(relativePath, http.FileServer(http.Dir(root)))
	urlPattern := relativePath + "/*filepath"
	engine.GET(urlPattern, func(c *Context) {
		handler.ServeHTTP(c.Writer, c.Request)
	})
}
